package com.synjones.handsetS8.fp;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.synjones.handsetS8.R;;
import com.synjones.handsetS8.Utils.util_File;
import com.synjones.handsetS8.Utils.util_info;
import com.synjones.handsetS8L.FingerprintReaderInterface;
import com.synjones.handsetS8L.FpFeature;
import com.synjones.handsetS8L.FpVerifyResult;
import com.synjones.handsetS8L.LDFpUsbModule;
import com.synjones.handsetS8L.MxFingerModule;
import com.synjones.handsetS8L.MyUtils;
import com.synjones.idcard.IDCardReaderRetInfo;
import com.synjones.reader.IDCardReaderModule;

public class FPTestActivity extends Activity {

    public static final String FP_DATA_PATH= Environment.getExternalStorageDirectory().getPath()+
            "/synjones/idcard/fp/";
    static final int SET_TEMPLATE_RET=0xaa;
    public static FingerprintReaderInterface fpModule;
    TextView tvCallBackMsg;
    TextView tvResult;
    EditText etThreshold;
    TextView tvCurrentTemplate;
    ImageView ivFingerImg;
    CheckBox cbShowImg;
    static final int MSG_WHAT_RESULT=1234;
    static final int MSG_WHAT_SHOW_IMG=4321;
    ProgressDialog progressDialog;
    volatile boolean readingCard=false;
    Handler handler=new Handler(){
        public void handleMessage(android.os.Message msg) {

            switch (msg.what){
                case MSG_WHAT_RESULT:
                    tvResult.setText(" "+msg.obj);
                    try {progressDialog.dismiss();} catch (Exception e) {}
                    break;
                case MSG_WHAT_SHOW_IMG:
                    ivFingerImg.setImageBitmap((Bitmap) msg.obj);
                    break;
                case FingerprintReaderInterface.MESSAGE_UPDATE_STATUS:
                    //指纹模块的消息
                    tvCallBackMsg.setText(" "+msg.obj);
                    try {progressDialog.setMessage(" "+msg.obj);} catch (Exception e) {}
                    break;
            }
            super.handleMessage(msg);
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fptest);

        fpModule= new MxFingerModule(this);
        fpModule.powerOn();

        tvCallBackMsg=(TextView)findViewById(R.id.tvMsg);
        tvResult=(TextView)findViewById(R.id.textView1);
        ivFingerImg=(ImageView)findViewById(R.id.ivFingerImg);
        cbShowImg=(CheckBox)findViewById(R.id.cbShowImg);
        etThreshold=(EditText)findViewById(R.id.etThreshold);
        etThreshold.setSelection(etThreshold.getText().toString().length());
        tvCurrentTemplate=(TextView)findViewById(R.id.tvCurrentTemplate);

        Button btn=(Button)findViewById(R.id.BtnOpen);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                int ret;
                ret=fpModule.open();
                if(ret==0)
                    sendMsg(MSG_WHAT_RESULT, "打开成功");
                else
                    sendMsg(MSG_WHAT_RESULT, "打开失败");
            }
        });

        btn=(Button)findViewById(R.id.btnClose);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                int ret=fpModule.close();
                if(ret==0)
                    sendMsg(MSG_WHAT_RESULT, "关闭成功");
                else
                    sendMsg(MSG_WHAT_RESULT, "关闭失败");

            }
        });

        btn=(Button)findViewById(R.id.btnScan);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                tvResult.setText("");
                tvCallBackMsg.setText("");
                setupProgressDialog("请将手指放到传感器上",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        fpModule.cancel();
                    }
                });
                final int downloadImg=cbShowImg.isChecked()?1:0;
                tvCurrentTemplate.setText("");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Looper.prepare();
                        FpFeature ret=fpModule.getFpFeature(downloadImg==1,10000);
                        if(ret!=null){
                            sendMsg(MSG_WHAT_RESULT, "录入结束");
                            sendMsg(MSG_WHAT_SHOW_IMG,ret.bmp );

                            if(ret.characteristic==null){
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        new  AlertDialog.Builder(FPTestActivity.this)
                                                .setTitle("提示")
                                                .setMessage("指纹质量差，请重新录入")
                                                .setNegativeButton("取消",null).show();
                                    }
                                });
                                return;
                            }

                            ListDataItem item=new ListDataItem();
                            item.id=SetTemplateActivity.getListSize()+1;
                            item.img=ret.bmp;
                            item.info="time="+ util_info.getNow()+","+ret.which;
                            item.template=ret.characteristic;

                            //util_File.writeByte2SdcardFile(FP_DATA_PATH+"template", fp_template);
                            SetTemplateActivity.addTemplate2List(item);

                            return;
                        }
                        sendMsg(MSG_WHAT_RESULT, "录入失败");
                    }
                }).start();
            }
        });


        btn=(Button)findViewById(R.id.btnVerify);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                tvResult.setText("");
                tvCallBackMsg.setText("");
                setupProgressDialog("请将手指放到传感器上",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        fpModule.cancel();
                    }
                });
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Looper.prepare();
                        FpVerifyResult ret=fpModule.verifyFp(getThreshold(),10000);
                        Log.e("Test", "ModuleVerify ret="+ret);

                        if(ret!=null){
                            String match=ret.isMatch?"匹配":"不匹配";
                            sendMsg(MSG_WHAT_RESULT, "对比结果："+match+",分数="+ret.score+"，ID="+ret.id);
                        }else{
                            sendMsg(MSG_WHAT_RESULT, "对比失败");
                        }

                    }
                }).start();
            }
        });


        btn=(Button)findViewById(R.id.btnDownloadTemplate);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                startActivityForResult(new Intent(FPTestActivity.this, SetTemplateActivity.class),SET_TEMPLATE_RET);
            }
        });


        btn=(Button)findViewById(R.id.btnGetIDCardFp);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                setupProgressDialog("请刷身份证……",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        readingCard=false;
                    }
                });
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        readingCard=true;
                        IDCardReaderModule idCardReaderModule=IDCardReaderModule.getInstance(FPTestActivity.this);
                        if(!idCardReaderModule.isOpen())
                            idCardReaderModule.open();

                        IDCardReaderRetInfo retInfo=null;
                        while(readingCard) {
                            retInfo = idCardReaderModule.getIDcardInfo(false, false, true);
                            if(retInfo!=null && retInfo.errCode==IDCardReaderRetInfo.ERROR_OK)
                                break;
                            MyUtils.sleep(500);
                        }
                        String result;
                        if(readingCard && retInfo.errCode== IDCardReaderRetInfo.ERROR_OK){
                            result=retInfo.card.getName()+retInfo.card.getIDCardNo();
                            if(retInfo.card.getFpCount()>0){
                                ListDataItem item=new ListDataItem(SetTemplateActivity.getListSize()+1,
                                        retInfo.card.getFp(1),
                                        null,
                                        retInfo.card.getName()+retInfo.card.getFpName(1),
                                        false);
                                SetTemplateActivity.addTemplate2List(item);
                                result+=",指位1："+retInfo.card.getFpName(1);
                                if(retInfo.card.getFpCount()==2){
                                    item=new ListDataItem(SetTemplateActivity.getListSize()+1,
                                            retInfo.card.getFp(2),
                                            null,
                                            retInfo.card.getName()+retInfo.card.getFpName(2),
                                            false);
                                    SetTemplateActivity.addTemplate2List(item);
                                    result+=",指位2："+retInfo.card.getFpName(2);
                                }
                            }else{
                                result+=",无指纹信息";
                            }
                        }else{
                            result="读卡失败";
                        }
                        readingCard=false;
                        sendMsg(MSG_WHAT_RESULT, result);
                        idCardReaderModule.close();
                        //fpModule.powerOn();
                    }
                }).start();
            }
        });

        //idCardReaderModule=new IDCardReaderModule(this);
        util_File.createFolderIfNotExists(FP_DATA_PATH);
    }

    private void sendMsg(int what,Object msg){
        handler.obtainMessage(what, msg).sendToTarget();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case SET_TEMPLATE_RET:
                if(resultCode==RESULT_OK){
                    tvCurrentTemplate.setText(data.getStringExtra(SetTemplateActivity.KEY_TEMPLATE_NAME));
                }
                break;
            default:
                return;
        }
    }

    private int getThreshold(){
        return Integer.parseInt(etThreshold.getText().toString());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        fpModule.powerOff();
        SetTemplateActivity.clearList();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    void setupProgressDialog(String msg, DialogInterface.OnClickListener listener){
        progressDialog = new ProgressDialog(FPTestActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(msg);
        progressDialog.setCancelable(false);
        if(listener!=null)
            progressDialog.setButton("取消", listener);
        progressDialog.show();
    }
}
